/*
 * Niiuzu
 * Copyright (C) 2011  Thierry Nowak
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.niiuzu.server.dao.impl;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.appengine.api.mail.MailService;
import com.google.appengine.api.mail.MailServiceFactory;
import com.google.appengine.api.mail.MailService.Message;
import com.niiuzu.server.dao.MailDao;
import com.niiuzu.server.dao.exception.DaoException;
import com.niiuzu.server.dao.model.MailRequest;

/**
 * Implémentation du gestionnaire d'emails.
 */
public class MailDaoImpl implements MailDao {

	private static final Logger LOGGER = Logger.getLogger(MailDaoImpl.class
			.getName());

	@Override
	public String getAppSenderMailAddress() throws DaoException {
		return "noreply@nii-uzu.appspotmail.com";
	}

	@Override
	public void sendMail(MailRequest mailRequest) throws DaoException {
		LOGGER.info("Début envoi d'un email : " + mailRequest);

		try {

			MailService mailService = getMailService();

			Message message = new Message();
			message.setSender(mailRequest.getSenderAddress());
			message.setTo(mailRequest.getReceiverAddress());
			message.setSubject(mailRequest.getTitle());
			message.setTextBody(mailRequest.getContent());

			mailService.send(message);

		} catch (Exception e) {
			LOGGER.log(Level.SEVERE, "Erreur lors de l'envoi de l'email : "
					+ mailRequest, e);
			throw new DaoException(e);
		} finally {
			LOGGER.info("Fin de l'envoi de l'email : " + mailRequest);
		}
	}

	/**
	 * Récupère une instance de {@link MailService}.
	 */
	public MailService getMailService() {
		if (mockedMailService != null) {
			return mockedMailService;
		}
		return MailServiceFactory.getMailService();
	}

	/* ********************************************************************** */
	/* ********************************************************************** */
	/* ********************************************************************** */

	private MailService mockedMailService;

	/**
	 * JUnit - Définit un mock pour {@link MailService}.
	 */
	void setMockedMailService(MailService mockedMailService) {
		this.mockedMailService = mockedMailService;
	}
}
